package com.you.mybatis.base.util;

import java.io.IOException;
import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

@Slf4j
public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory = null;
    private static final String MYBATIS_CONFIG_LOCATION = "mybatis/mybatis-config.xml";

    private MybatisUtil() {
    }

    public static SqlSessionFactory getSqlSessionFactoryInstance() {
        return getSqlSessionFactoryInstance(MYBATIS_CONFIG_LOCATION);
    }

    public static SqlSessionFactory getSqlSessionFactoryInstance(String resource) {
        if (sqlSessionFactory != null) {
            return sqlSessionFactory;
        }

        InputStream inputStream = null;

        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            log.error("获取sqlSessionFactory异常, 请检查配置文件位置是否正确，", e);
        } finally {
            CloseUtil.close(inputStream);
        }
        return sqlSessionFactory;
    }
}
